package com.xxl.job.admin.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.util.Hashtable;

/*
*
* AD域校验
*
* */
@Service
public class LdapService {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(LdapService.class);
    
    //@Value("${ldap.factory.initial}")
    private String factoryInitial;
    
    //@Value("${ldap.provider.url}")
    private String providerUrl;
    
    //@Value("${ldap.security.principal}")
    private String principal;
    
   // @Value("${ldap.security.credentials}")
    private String credentials;
    
   // @Value("${ldap.security.authentication}")
    private String authentication;
    
    public boolean authenticate(String userName, String passWord) {
//        LOGGER.info("authenticate , userName:{}", userName);
//        boolean result = false;
//        LdapContext ctx = null;
//        try {
//            if (!StringUtils.isEmpty(passWord) && !StringUtils.isEmpty(userName)) {
//                Hashtable<String, String> env = new Hashtable<>();
//                env.put(Context.INITIAL_CONTEXT_FACTORY, factoryInitial);
//                env.put(Context.PROVIDER_URL, providerUrl);
//                env.put(Context.SECURITY_PRINCIPAL, principal + userName);
//                env.put(Context.SECURITY_CREDENTIALS, credentials + passWord);
//                env.put(Context.SECURITY_AUTHENTICATION, authentication);
//                ctx = new InitialLdapContext(env, null);
//                result = true;
//            }
//        } catch (AuthenticationException e) {
//            LOGGER.error("AuthenticationException: ", e);
//        } catch (NamingException e) {
//            LOGGER.error("NamingException: ", e);
//        } finally {
//            // 关闭LdapContext
//            if (ctx != null) {
//                try {
//                    ctx.close();
//                } catch (NamingException e) {
//                    LOGGER.error(e.toString());
//                }
//            }
//        }
//        LOGGER.info("authenticate end , result:{}", result);
//        return result;
        return true;
    }
}
